import React,{Component} from 'react';
import PropTypes from 'prop-types';
import * as RecordAPI from '../utils/RecordAPI'

export default class  Record extends Component{
    constructor(props){
        super(props);
        this.state={
            isEdit: false
        }
    }

    handleToggle(){
        this.setState({
            isEdit: !this.state.isEdit
        })
    }

    handleEdit(e){
        e.preventDefault()
        const record={
            date: this.refs.date.value,
            title: this.refs.title.value, 
            amount: parseInt(this.refs.amount.value)
        }
        RecordAPI.update(record)
        .then(res=>{
            this.setState({isEdit: false})
            this.props.handleEditRecord(this.props.record,res.data)//此处将被编辑框原本的值传入handleEditRecord作为第一个参数，将更新后的值作为第二个参数
            }
        )
        .catch(err=>console.log(err.message))
    }

    handleDelete(e){
        e.preventDefault();
        RecordAPI.remove(this.props.record.id).then(res=>{
            console.log(res.data)
            this.props.handleDelete(this.props.record)
        })
        
    }

    RecordRow(){
        return (
            <tr>
                <td>{this.props.record.date}</td>
                <td>{this.props.record.title}</td>
                <td>{this.props.record.amount}</td>
                <td>
                    <button className='btn btn-info mr-2' onClick={this.handleToggle.bind(this)}>Edit</button>
                    <button className='btn btn-danger' onClick={this.handleDelete.bind(this)}>Delete</button>
                </td>
            </tr>
        )
    }

    RecordEdit(){
        return (
            <tr>
                <td><input className='form-control' defaultValue={this.props.record.date} ref='date'></input></td>
                <td><input className='form-control' defaultValue={this.props.record.title} ref='title'></input></td>
                <td><input className='form-control' defaultValue={this.props.record.amount} ref='amount'></input></td>
                <td>
                    <button className='btn btn-info mr-2' onClick={this.handleEdit.bind(this)}>Update</button>
                    <button className='btn btn-danger' onClick={this.handleToggle.bind(this)}>Cancel</button>
                </td>
            </tr>
        )
    }

    render(){
        if(this.state.isEdit){
            return this.RecordEdit()
        }else{
            return this.RecordRow()
        }
    }
    
}


Record.propTypes={
    id: PropTypes.number,
    date: PropTypes.string,
    title: PropTypes.string,
    amount: PropTypes.number
}